#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <linux/netlink.h>
#include <dirent.h>
#include <sys/statfs.h>

int init_socket()
{
    struct sockaddr_nl snl;
    const int buffersize = 1024;
    int retval;
    int sock_id;

    memset(&snl, 0, sizeof(struct sockaddr_nl));
    snl.nl_family = AF_NETLINK;
    snl.nl_pid = getpid();
    snl.nl_groups = 1;

    sock_id = socket(PF_NETLINK, 
                     SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
    if (sock_id == -1) {
        printf("sock error : %m\n");
        exit(-1);
    }

    setsockopt(sock_id, SOL_SOCKET, 
               SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
    retval = bind(sock_id, 
                  (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
    if (retval == -1) {
        printf("bind error:%m\n");
        close(sock_id);
        exit(-1);
    }

    return sock_id;
}

// 该函数主要作用时检测u盘的 总空间,剩余空间,剩余空间百分比
double get_disk_free_space_percent(const char * pdisk, 
                                   double * freespace, 
                                   double * totalspace)
{
    struct statfs disk_statfs;
    double free_space_percent = 0;

    if (statfs(pdisk, &disk_statfs) == 0) {
        *freespace = 
            (disk_statfs.f_bsize * disk_statfs.f_bfree) / (1024 * 1024 * 1024.0);
        *totalspace = 
            (disk_statfs.f_bsize * disk_statfs.f_blocks) / (1024 * 1024 * 1024.0);
    }

    return free_space_percent = (*freespace) / (*totalspace) * 100;
}

#define BUF_SIZE 2048

int main()
{
    DIR *dp;
    double f = 0;
    double t = 0;
    double percent = 0;
    const char * path = "/mnt";
    int sd = init_socket();

    while (1) {
        char buf[BUF_SIZE] = {0};
        recv(sd, &buf, sizeof(buf), 0);
        if (!memcmp(buf, "add@", 4) /* && !memcmp(&buf[strlen(buf) - 4], "/sdb", 4) */) {
            printf("Found U disk\n");
            break;
        }
    }

    printf("is open u-disk Y/N:\n");
    char c;
    scanf("%c", &c);
    if (c == 'y' || c == 'Y') {
        if ((dp = opendir(path)) == NULL) 
            printf("open path fail.\n");
        else
            system("ls -l /mnt");
    }
    else if (c == 'N' || c == 'n') {
        percent = get_disk_free_space_percent(path, &f, &t);
        printf("u-dsik free space: %.2f\n", f);
        printf("u-disk total space: %.2f\n", t);
        printf("u-disk free space percent:%0.2f%%\n", percent);
    }

    return 0;
}
